//
//  SreingExtension.swift
//  JKTools
//
//  Created by 姜奎 on 2024/4/25.
//

import Foundation

public
extension String {
    func isAsciiOnly() -> Bool {
        return !self.contains { $0 >= "\u{0080}" }
    }
    
    func URLEncode() -> String {
        var allowedCharacterSet = CharacterSet.urlQueryAllowed
        
        allowedCharacterSet.remove(charactersIn: ":#[]@!$&'()*+,;=?/")
        
        return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? ""
    }
    
    func URLDecode() -> String {
        return self.removingPercentEncoding ?? ""
    }
    
    func unixFormat() -> String {
        let gmtTimeStamp: TimeInterval = TimeInterval(self) ?? Date().timeIntervalSince1970
        let dateFromTimestamp = Date(timeIntervalSince1970: gmtTimeStamp)
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"  // 根据需要调整日期时间格式
        dateFormatter.locale = Locale(identifier: "zh_CN")  // 设置中文本地化以正确显示中文月份和星期等

        let beijingTimeString = dateFormatter.string(from: dateFromTimestamp)
        
        return beijingTimeString
    }
    
    func unixTimestamp() -> String {
        let dateFormatter = DateFormatter()
          // 根据需要调整日期时间格式
        dateFormatter.locale = Locale(identifier: "zh_CN")  // 设置中文本地化以正确显示中文月份和星期等

        
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        if let beijingTime = dateFormatter.date(from: self)?.timeIntervalSince1970 {
            return String(Int64(beijingTime))
        }
        
        dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
        if let beijingTime = dateFormatter.date(from: self)?.timeIntervalSince1970 {
            return String(Int64(beijingTime))
        }
        
        dateFormatter.dateFormat = "yyyy/MM/dd"
        if let beijingTime = dateFormatter.date(from: self)?.timeIntervalSince1970 {
            return String(Int64(beijingTime))
        }
        
        return ""
    }
    
}
public
extension String {
    func convertRelativePath(absolutPath: String = FileManager.default.currentDirectoryPath) -> String {
        
        if self.hasPrefix("/") {
            return self
        }
        
        if self.hasPrefix("~") {
            return (self as NSString).expandingTildeInPath
        }
        
        var url = URL(fileURLWithPath: absolutPath)
        
        if let currentDirectory = try? url.currentDirectory() {
            url = currentDirectory
        }
        
        var path = self
        
        while path.hasPrefix("./") {
            let index = path.index(path.startIndex, offsetBy: 2)
            path = String(path[index...])
        }
        
        while path.hasPrefix("../") {
            let index = path.index(path.startIndex, offsetBy: 3)
            path = String(path[index...])
            url.deleteLastPathComponent()
        }
        
        return url.appendingPathComponent(path).path
        
    }
}

import CommonCrypto
public
extension String {
    var MD5: String {
        if self.isEmpty {
            return self
        }
        let length = Int(CC_MD5_DIGEST_LENGTH)
        let messageData = self.data(using:.utf8)!
        var digestData = Data(count: length)

        _ = digestData.withUnsafeMutableBytes { digestBytes -> UInt8 in
            messageData.withUnsafeBytes { messageBytes -> UInt8 in
                if let messageBytesBaseAddress = messageBytes.baseAddress, let digestBytesBlindMemory = digestBytes.bindMemory(to: UInt8.self).baseAddress {
                    let messageLength = CC_LONG(messageData.count)
                    CC_SHA256(messageBytesBaseAddress, messageLength, digestBytesBlindMemory)
                }
                return 0
            }
        }
        return digestData.map { String(format: "%02hhx", $0) }.joined()
    }
}

public
extension String {
    func destination() -> String {
        return URL(fileURLWithPath: self).lastPathComponent
    }
}

